package com.xiaodimall.beforesys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaodimall.beforesys.mapper.GoodsMapper;
import com.xiaodimall.beforesys.mapper.ShoppingCartItemMapper;
import com.xiaodimall.beforesys.pojo.Goods;
import com.xiaodimall.beforesys.pojo.ShoppingCartItem;
import com.xiaodimall.beforesys.pojo.User;
import com.xiaodimall.beforesys.service.CartService;
import com.xiaodimall.common.Constants;
import com.xiaodimall.common.ServiceResultEnum;
import com.xiaodimall.utils.BeanUtil;
import com.xiaodimall.utils.Result;
import com.xiaodimall.utils.ResultGenerator;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author wyc
 * @description
 * @ClassName CartServiceImpl
 * @date 2022/11/26 14:57
 */
@Service
public class CartServiceImpl implements CartService {

    //注入持久层对象
    @Resource
    ShoppingCartItemMapper shoppingCartItemMapper;
    //注入商品持久层对象
    @Resource
    GoodsMapper goodsMapper;



    /**
     * 根据商品id把商品添加到购物车
     * @author WYC
     * @param shoppingCartItem 封装这商品id和商品数量
     * @param httpSession
     * @return: 返回结果集
     * @date: 2022/11/26 15:35
     */
    @Override
    public String addGoodsCart(ShoppingCartItem shoppingCartItem, HttpSession httpSession) {
        //获取session域的数据
        User user = (User) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        if (user == null) {
            return ServiceResultEnum.SESSION_ERROR_NULL.getResult();
        }
        //设置用户id
        shoppingCartItem.setUserId(user.getUserId());
        ShoppingCartItem temp = shoppingCartItemMapper.selectOne(
                new QueryWrapper<ShoppingCartItem>()
                        .eq("user_Id", shoppingCartItem.getUserId())
                        .eq("goods_Id", shoppingCartItem.getGoodsId()).eq("is_deleted",0));
        if (temp != null) {
            //已存在则修改该商品的数量
            temp.setGoodsCount(shoppingCartItem.getGoodsCount());
            return updateCartItem(temp);
        }
        Goods newGoods = goodsMapper.selectById(shoppingCartItem.getGoodsId());
        //判断商品是否还存在
        if (newGoods == null) {
            return ServiceResultEnum.GOODS_NOT_EXIST.getResult();
        }
        //添加商品
        int row = shoppingCartItemMapper.insert(shoppingCartItem);
        if (row > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }


    /**
     * 根据id修改商品的购买数量
     * @author WYC
     * @param shoppingCartItem
     * @return: 结果集
     * @date: 2022/11/28 10:41
     */
    @Override
    public String updateCartItem(ShoppingCartItem shoppingCartItem) {
        //查询出对应的商品数量
        ShoppingCartItem newCartGood = shoppingCartItemMapper.selectOne(
                new QueryWrapper<ShoppingCartItem>()
                        .eq("cart_item_id",shoppingCartItem.getCartItemId())
                        .eq("is_deleted",0));
        if (newCartGood == null) {
            return ServiceResultEnum.DATA_NOT_EXIST.getResult();
        }
        //修改商品数量
        newCartGood.setGoodsCount(shoppingCartItem.getGoodsCount());
        newCartGood.setUpdateTime(new Date());
        //修改记录
        int row = shoppingCartItemMapper.updateById(newCartGood);
        if (row > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    /**
     * 获取购物车页面的方法
     * @author WYC
     * @param request
     * @param httpSession
     * @return: 返回数据到购物车页面
     * @date: 2022/11/28 17:06
     */
    @Override
    public String getCartMsg(HttpServletRequest request, HttpSession httpSession) {

        //取出数据
        Map<String, Object> map = showCartMsg(httpSession);

        List<Goods> list = (List<Goods>) map.get("list");
        int priceTotal =(int) map.get("price");
        int itemsTotal = (int) map.get("num");
        if (!CollectionUtils.isEmpty(list)) {
            if (priceTotal < 1) {
                return "error/error_5xx";
            }

            if (itemsTotal < 1) {
                return "error/error_5xx";
            }
        }
        //绑定数据
        request.setAttribute("itemsTotal", itemsTotal);
        request.setAttribute("priceTotal", priceTotal);
        request.setAttribute("myShoppingCartItems", list);
        return "mall/cart";

    }

    /**
     * 获取购物车数据的方法
     * @author WYC
     * @param session
     * @return: 返回map集合
     * @date: 2022/11/28 17:05
     */
    public Map<String,Object> showCartMsg(HttpSession session){
        HashMap<String, Object> map = new HashMap<>();
        User user = (User) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
        int itemsTotal = 0;
        int priceTotal = 0;
        //查询出用户的购物车商品信息
        List<ShoppingCartItem> myCartGoods = shoppingCartItemMapper.selectList(
                new QueryWrapper<ShoppingCartItem>().eq("user_id",user.getUserId()).eq("is_deleted",0));
        //创建集合封装数据
        ArrayList<Goods> goodsList= new ArrayList<>();
        for (ShoppingCartItem myCartGood : myCartGoods) {
            //获取商品id
            Long goodsId = myCartGood.getGoodsId();
            //根据商品id查询出对应的商品信息
            Goods goods = goodsMapper.selectById(goodsId);

            //封装购物车id
            goods.setCartItemId(myCartGood.getCartItemId());
            String goodsName = goods.getGoodsName();
            //封装购物车的商品数量
            Integer goodsCount = myCartGood.getGoodsCount();
            goods.setGoodsCount(goodsCount);
            //计算所有商品的总价
            priceTotal+=goods.getSellingPrice()*goodsCount;
            //
            if (goodsName.length() > 28) {
                goodsName = goodsName.substring(0, 28) + "...";
                goods.setGoodsName(goodsName);
                goods.setSellingPrice(goods.getSellingPrice());
            }
            //购物项总数
            itemsTotal+=1;
            //把数据添加到集合
            goodsList.add(goods);
        }
        //绑定数据
        map.put("list",goodsList);
        map.put("num",itemsTotal);
        map.put("price",priceTotal);
        return map;
    }



    /**
     * 根据购物车商品id删除商品
     * @author WYC
     * @param shoppingCartItemId
     * @param session
     * @return: 结果集
     * @date: 2022/11/28 20:35
     */
    @Override
    public Result DelCartGood(Long shoppingCartItemId, HttpSession session) {
        User user = (User) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
        //判断是否会话超时
        if (user == null) {
            return ResultGenerator.genFailResult(ServiceResultEnum.SESSION_ERROR_NULL.getResult());
        }
        //这里直接修改删除状态 0表示未删除 1表示以删除
        int row = shoppingCartItemMapper.update(new ShoppingCartItem().setIsDeleted(1),
                new QueryWrapper<ShoppingCartItem>()
                        .eq("user_id",user.getUserId())
                        .eq("cart_item_id", shoppingCartItemId));
        //删除成功
        if (row>0) {
            return ResultGenerator.genSuccessResult();
        }
        //删除失败
        return ResultGenerator.genFailResult(ServiceResultEnum.OPERATE_ERROR.getResult());
    }


    /**
     * 获取购物车信息到订单结算页面
     * @author WYC
     * @param request
     * @param httpSession
     * @return: 返回到结算页面 mall/order-settle.html
     * @date: 2022/11/28 20:50
     */
    @Override
    public String toSettlePage(HttpServletRequest request, HttpSession httpSession) {
        //获取购物车信息
        Map<String, Object> map = showCartMsg(httpSession);
        List<Goods> goods = (List<Goods>) map.get("list");
        //获取总价
        int priceTotal = (int) map.get("price");

        if (StringUtils.isEmpty(goods)) {
            //无数据则不跳转至结算页
            return "/shop-cart";
        }
        if (priceTotal < 1) {
            return "error/error_5xx";
        }
        //绑定数据
        request.setAttribute("priceTotal", priceTotal);
        request.setAttribute("myShoppingCartItems", goods);

        return "mall/order-settle";
    }


}
